package LinkedList.旋转链表;

import LinkedList.ListNode;

public class Test {
    public ListNode rotateRight(ListNode head, int k) {
        if(k == 0 || head == null || head.next == null) {
            return head;
        }
        // 求链表长度和找到最后一个节点
        int count = 1;
        ListNode end = head;
        while(end.next != null) {
            count++;
            end = end.next;
        }
        int k2 = k % count; // 实际反转的次数
        if(k2 == 0) {
            return head;
        }

        end.next = head;
        // 找新的尾部
        int n = count - k2;
        ListNode newEnd = head;
        for(int i = 1; i < n; i++) {
            newEnd = newEnd.next;
        }
        head = newEnd.next;
        newEnd.next = null;

        return head;
    }
}
